/**
 * @Author: easten
 * @Created: 2024-08-04 08:50:55
 * @Description: 报警声音组件
 *
 */
import React, { useEffect, useRef } from "react";
import wav from "assets/alarm.wav";
import mp3 from "assets/offline.mp3";
type AlarmSoundingProps = {
  // 是否开启报警声音
  isAlarmSounding: boolean;
  // 是否开启离线提示声音
  isOfflineSounding?: boolean;
  // 是否报警
  isAlarm: boolean;
  // 是否离线
  isOffline?: boolean;
};
const AlarmSounding: React.FC<AlarmSoundingProps> = (
  props: AlarmSoundingProps
) => {
  const { isAlarmSounding, isOfflineSounding, isAlarm, isOffline } = props;
  const ref = useRef<HTMLAudioElement>(null);
  const off = useRef<HTMLAudioElement>(null);
  useEffect(() => {
    return () => {
      if (ref.current) {
        ref.current?.pause();
      }
      if (off.current) {
        off.current?.pause();
      }
    };
  }, []);

  useEffect(() => {
    if (isAlarmSounding) {
      // 开启了声音
      if (isAlarm) {
        // 报警了
        if (ref.current) {
          ref.current.play();
        }
      } else {
        // 没有报警
        ref.current?.pause();
        if (ref.current?.currentTime) ref.current.currentTime = 0;
      }
    } else {
      ref.current?.pause();
      if (ref.current?.currentTime) ref.current.currentTime = 0;
    }
  }, [isAlarmSounding, isAlarm]);
  useEffect(() => {
    if (isOfflineSounding) {
      // 开启了声音
      if (isOffline) {
        // 离线了
        if (off.current) {
          off.current.play();
        }
      } else {
        // 没有离线
        off.current?.pause();
        if (off.current?.currentTime) off.current.currentTime = 0;
      }
    } else {
      off.current?.pause();
      if (off.current?.currentTime) off.current.currentTime = 0;
    }
  }, [isOfflineSounding, isOffline]);
  return (
    <div>
      <audio src={wav} loop ref={ref} />
      <audio src={mp3} loop ref={off} />
    </div>
  );
};
export default AlarmSounding;
